<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
  <button @click="getNum">按钮</button>
  <button @click="getMul">按钮1</button>
  <button @click="getSum">按钮2</button>
  <button @click="getFilter">按钮3</button>
  <button @click="getMap">按钮4</button>
  <button @click="getReduce">按钮5</button>
  <button @click="getEasy">按钮6</button>
  <button @click="getEasy2">按钮7</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const vm = new Vue({
    el: '#app',
    data: {
      nums: [11, 22, 55, 98, 452, 174]
    },
    methods: {
      //1.取出需求小于100的数字
      getNum() {
        for (let item in this.nums) {
          if (this.nums[item] < 100) {
            console.log(this.nums[item]);
          }
        }
      },
      //2.将所有小于100的数全部*2
      getMul() {
        for (let item in this.nums) {
          if (this.nums[item] < 100) {
            console.log(this.nums[item] * 2);
          }
        }
      },
      //3.将所有的数字相加得到结果
      getSum() {
        let sum = 0
        for (let item in this.nums) {
          sum += this.nums[item]
        }
        console.log(sum)
      },
      //filter/map/reduce的使用
      getFilter() {
        //filter的回调函数有一个要求：必须返回一个boolean值
        //当返回true时，函数内部会自动将这次回调的n加入到新的数组中
        //当返回false时，函数内部会过滤到此次的n
        let newnums = this.nums.filter(function (n) {
          return n < 100
        })
        console.log(newnums);
      },
      getMap() {
        //map得到
        let newnums = this.nums.map(function (n) {
          return n * 2
        })
        console.log(newnums);
      },
      getReduce() {
        //reduce函数，对数组中的所有内容进行汇总
        //第一次：preValue:0 n:11
        //第二次：preValue 11 n:22
        //以此类推 进行求和操作
        let newnums = this.nums.reduce(function (preValue, n) {
          return preValue + n
        }, 0)//该值0是给preValue赋初始值
        console.log(newnums);
      },
      getEasy() {
        let total = this.nums.filter(function (n) {
          return n < 100
        }).map(function (n) {
          return n * 2
        }).reduce(function (preValue, n) {
          return preValue + n
        }, 0)
        console.log(total);
      },
      getEasy2() {
        let total = this.nums.filter(n => n < 100).map(n => n * 2).reduce((pre, n) => pre + n)
        console.log(total);
      }
    }
  })
</script>

</body>
</html>